<script lang="ts" setup>
import Taro from '@tarojs/taro';
import { wxLogin } from '@/service';
import { useAppStore, useAuthStore } from '@/store';
import { useRouterPush } from '@/composables';
import { showErrorMsg } from '@/service/request/helpers';

const authStore = useAuthStore();
const appStore = useAppStore();
const { toHome } = useRouterPush();

const getPhoneNumber = (e: { detail: { code: string; encryptedData: string; errMsg: string; iv: string } }) => {
  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    Taro.showLoading({ title: '登录中' });
    const { code } = e.detail;
    wxLogin(code)
      .then((res: Service.SuccessResult) => {
        Taro.hideLoading();
        authStore.setAuthStore(res.success!);
        // 路径前必须加斜杠，这里是个坑
        appStore.setActiveTab('/pages/home/index');
        toHome();
      })
      .catch((err: Service.RequestError) => {
        Taro.hideLoading();
        showErrorMsg(err.message);
      });
  } else {
    Taro.hideLoading();
    Taro.showModal({
      title: '警告',
      content: '您点击了拒绝授权，将无法进入小程序，请授权后进入',
      showCancel: false,
      confirmText: '返回授权'
    });
  }
};
</script>

<template>
  <div class="login-container">
    <nut-avatar size="large" shape="square" class="login-logo">
      <img
        alt=""
        src="https://img12.360buyimg.com/imagetools/jfs/t1/196430/38/8105/14329/60c806a4Ed506298a/e6de9fb7b8490f38.png"
      />
    </nut-avatar>
    <div class="login-title">礼上来往</div>
    <nut-button
      color="#F44336"
      class="login-button none-border-btn wx-btn"
      open-type="getPhoneNumber"
      @getphonenumber="getPhoneNumber"
    >
      <template #icon>
        <div class="text-25px i-local-wx" />
      </template>
      微信一键登录
    </nut-button>
  </div>
</template>

<style lang="scss">
.login-container {
  width: 100vw;
  height: 100vh;
  background-color: #fafafa;
  text-align: center;

  .login-logo {
    margin-top: 100px;
  }

  .login-title {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    margin: 10px;
    font-weight: bold;
    color: #595757;
  }

  .wx-btn {
    margin-top: 120px;
  }

  .none-border-btn {
    border: none;
  }

  .none-border-btn:active {
    border: none;
  }
}
</style>
